package com.tbit.main.controller;

import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.BatteryConstant;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.dao.core.BatteryLoseDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedList;
import java.util.List;

/**
 * 电池操作
 *
 * @author LMY
 * @create 2021-05-27 10:04
 */
@RestController
@RequestMapping("/batteryController")
public class BatteryController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private BatteryService batteryService;
    @Autowired
    private BatteryLogService batteryLogService;
    @Autowired
    private BatteryGroupBoundService batteryGroupBoundService;
    @Autowired
    private DataService dataService;
    @Autowired
    private BatteryModelChartService batteryModelChartService;
    @Autowired
    private BatteryGroupService batteryGroupService;
    @Autowired
    private MachineLoseService machineLoseService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private BatteryLoseDao batteryLoseDao;
    @Autowired
    private BmsBatteryService bmsBatteryService;
    @Autowired
    private BmsAbnormalService bmsAbnormalService;

    /**
     * 电池新增
     */
    @RequestMapping("/insert")
    public JsonResult insert(String token, Battery battery) {

        Assert.notNull(battery.getAccountId(), "AccountUser.agentId.notNull");
        Assert.notNull(battery.getBatteryModelId(), "BatteryModel.batterModelId.notNull");
        Assert.notNull(battery.getBatteryNO(), "Battery.batteryNO.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        battery.setAddAccountUserId(accountUser.getAccountUserId());
        battery.setAccountUserId(accountUser.getAccountUserId());
        batteryService.insert(battery);

        batteryLogService.insert(battery.getBatteryNO(), accountUser.getAccountUserId(), BatteryConstant.Battery_Type_TJ, null);

        return JsonResult.succ();
    }

    /**
     * 电池删除
     */
    @RequestMapping("/del")
    @OperateLog(module = ModuleEnum.BATTERY, methods = MethodEnum.BATTERY_DEL)
    public JsonResult del(String token, Integer batteryId) {
        Assert.notNull(batteryId, "Battery.batteryId.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        Battery battery = batteryService.getBatteryId(batteryId);

        batteryService.auth(accountUser.getAgents(), batteryId);

        if (battery.getState().equals(BatteryConstant.Battery_State_KGZ)) {
            batteryLogService.insert(battery.getBatteryNO(), accountUser.getAccountUserId(), BatteryConstant.Battery_Type_YC, null);

            batteryService.del(batteryId);

            bmsBatteryService.delete(battery.getBatteryNO());
            bmsAbnormalService.delete(battery.getBatteryNO());
        } else {
            throw new BaseException("Battery.KG.not");
        }
        return JsonResult.succ();
    }

    /**
     * 添加/删除（丢失，报废 电池添加/删除 电池状态校验）
     */
    @RequestMapping("/lose")
    public JsonResult lose(String token, String batteryNO, Integer type, Integer state, String remark, String userCode, String loseTime) {


        Assert.notNull(batteryNO, "Battery.batteryNO.notNull");
        Assert.notNull(type, "Battery.type.notNull");
        Assert.notNull(state, "Battery.state.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        batteryService.auth(accountUser.getAgents(), dataService.getBatteryId(batteryNO));
        /**添加*/
        if (type == 1) {
            if (state.equals(BatteryConstant.Battery_State_DS)) {

                Battery batteryDB = batteryService.getByNO(batteryNO);
                if (batteryDB.getState().equals(BatteryConstant.Battery_State_DS)) {
                    throw new BaseException("battery.lose.exit");
                }

                /**上报丢失*/
                if (userCode != null) {
                    MachineLose machineLose = new MachineLose();
                    /**查询设备信息*/
                    Machine machine = machineService.getByUseCode(userCode);
                    if (machine == null) {
                        throw new BaseException("Machine.notExist");
                    }
                    /**设备权限判断*/
                    machineService.auth(accountUser.getAgents(), machine.getMachineId());
                    MachineLose machineLoseDB = machineLoseService.getAccountIdAndUserCode(machine.getAccountId(), userCode);
                    if (machineLoseDB == null) {
                        machineLose.setAccountId(machine.getAccountId());
                        machineLose.setAddMan(accountUser.getName());
                        machineLose.setMachineId(machine.getMachineId());
                        machineLose.setMachineNO(machine.getMachineNO());
                        machineLose.setUserCode(userCode);
                        machineLose.setLoseTime(loseTime);
                        machineLose.setReason(batteryNO + "电池丢失，上报车辆丢失");
                        machineLoseService.insert(machineLose);
                    }


                    batteryService.updateIdState(batteryNO, null, accountUser.getAccountUserId(), state, remark);
                } else {
                    if (batteryDB != null) {
                        batteryService.updateIdState(batteryNO, "1", accountUser.getAccountUserId(), state, remark);
                    }
                }

                BatteryLose batteryLose = new BatteryLose();
                batteryLose.setAccountId(batteryDB.getAccountId());
                batteryLose.setAddMan(accountUser.getName());
                batteryLose.setBatteryId(batteryDB.getBatteryId());
                batteryLose.setBatteryNO(batteryNO);
                batteryLose.setLoseTime(loseTime);
                batteryLose.setReason(remark + "电池丢失，上报车辆丢失");
                batteryLoseDao.insert(batteryLose);

                batteryLogService.insert(batteryNO, accountUser.getAccountUserId(), BatteryConstant.Battery_Type_DS, remark);

            } else if (state.equals(BatteryConstant.Battery_State_BF)) {
                batteryService.updateIdState(batteryNO, null, accountUser.getAccountUserId(), state, remark);
                batteryLogService.insert(batteryNO, accountUser.getAccountUserId(), BatteryConstant.Battery_Type_BF, remark);
            }

            List<BatteryGroupBound> batteryGroupBounds = batteryGroupBoundService.getNOs(batteryNO);
            if (batteryGroupBounds != null && batteryGroupBounds.size() > 0) {
                if (batteryGroupBounds.size() == 1) {
                    batteryGroupService.del(batteryGroupBounds.get(0).getId());
                } else {
                    batteryGroupBoundService.delBatteryNO(batteryNO);
                }
            }

        } else {
            /**删除*/
            if (state.equals(BatteryConstant.Battery_State_DS)) {
                if (userCode != null) {
                    batteryService.updateIdState(batteryNO, null, accountUser.getAccountUserId(), BatteryConstant.Battery_State_DRK, remark);
                    machineLoseService.del(userCode);
                } else {
                    Battery battery = batteryService.getByNO(batteryNO);
                    if (battery != null) {
                        batteryService.updateIdState(batteryNO, "1", accountUser.getAccountUserId(), BatteryConstant.Battery_State_DRK, remark);
                    }
                }

                batteryLoseDao.del(batteryNO);

                batteryLogService.insert(batteryNO, accountUser.getAccountUserId(), BatteryConstant.Battery_Type_XH, remark);
            } else if (state.equals(BatteryConstant.Battery_State_BF)) {
                batteryService.updateIdState(batteryNO, null, accountUser.getAccountUserId(), BatteryConstant.Battery_State_DRK, remark);
                batteryLogService.insert(batteryNO, accountUser.getAccountUserId(), BatteryConstant.Battery_State_DRK, remark);
            }

        }
        return JsonResult.succ();
    }

    /**
     * 解绑电池
     */
    @RequestMapping("/untie")
    public JsonResult untie(String token, String batteryNO, String userCode, String remark) {

        Assert.notNull(batteryNO, "Battery.batteryNO.notNull");
        Assert.notNull(remark, "System.remark.notNull");
        Assert.notNull(userCode, "Machine.userCode.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        batteryService.auth(accountUser.getAgents(), dataService.getBatteryId(batteryNO));

        Battery battery = batteryService.getByNO(batteryNO);

        if (battery.getUserCode() == null || !battery.getUserCode().equals(userCode)) {
            throw new BaseException("Battery.userCode.not");
        }

        batteryService.updateIdState(batteryNO, userCode, accountUser.getAccountUserId(), BatteryConstant.Battery_State_DRK, remark);

        batteryLogService.insert(batteryNO, accountUser.getAccountUserId(), BatteryConstant.Battery_Type_JB, remark+"车辆编码 :"+userCode);

        return JsonResult.succ();
    }

    /**
     * 根据id/no查询单个电池详情
     */
    @RequestMapping("/getId")
    public JsonResult getId(String token, Integer batteryId, String batteryNO) {

        Battery battery = new Battery();
        if (batteryId != null) {
            battery = batteryService.getBatteryId(batteryId);
        } else {
            battery = batteryService.getByNO(batteryNO);
        }

        BatteryModelChart batteryModelChart = batteryModelChartService.getByModelId(battery.getBatteryModelId());
        if (batteryModelChart != null) {
            battery.setBatteryModel(batteryModelChart.getBatteryModel());
        }

        return JsonResult.succ(battery);
    }

    /**
     * 根据车辆编号查询
     */
    @RequestMapping("/getUserCode")
    public JsonResult getUserCode(String token, String userCode) {


        AccountUser accountUser = tokenService.getAccount(token);

        /**设备权限判断*/
        machineService.auth(accountUser.getAgents(), dataService.getMachineIdUserCode(userCode));

        Battery battery = batteryService.getByMachineId(dataService.getMachineIdUserCode(userCode));

        return JsonResult.succ(battery);
    }

    /**
     * 根据运营区域查询,不查丢失,报废电池
     */
    @RequestMapping("/getState")
    public JsonResult getState(String token, Integer accountId, Integer state, Integer batteryModelId,
                               @RequestParam(defaultValue = "1") Integer pageNO, @RequestParam(defaultValue = "10") Integer rowCount) {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        Integer parkCount = batteryService.getByAccountIdCount(accountId, state, batteryModelId);

        List<Battery> batteries = new LinkedList<>();
        if (parkCount > 0) {
            batteries = batteryService.getByAccountId(accountId, state, batteryModelId, pageNO, rowCount);
        }

        return JsonResult.succ(parkCount, batteries);
    }

    /**
     * 根据运营区域查询,查询丢失，报废电池
     */
    @RequestMapping("/getLose")
    public JsonResult getLose(String token, Integer accountId) {
        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        List<Battery> batteries = batteryService.getByAccountIdLose(accountId);


        return JsonResult.succ(batteries);
    }

    /**
     * 根据no查询运维人员归属的电池（查询移交电池）
     *
     * @return
     */
    @RequestMapping("/getRemove")
    public JsonResult getRemove(String token, String batteryNO) {
        Assert.notNull(batteryNO, "Battery.batteryNO.notNull");

        AccountUser accountUser = tokenService.getAccount(token);

        batteryService.auth(accountUser.getAgents(), dataService.getBatteryId(batteryNO));
        List<Battery> batteries = batteryGroupBoundService.getBatteryNO(batteryNO);
        return JsonResult.succ(batteries);
    }

    /**
     * 根据no查询运维人员归属的电池（查询归还电池）自己，别人
     *
     * @return
     */
    @RequestMapping("/getReturn")
    public JsonResult getReturn(String token, Integer state, String batteryNO, Integer userMainId, Integer accountId) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");

        Battery battery = null;

        AccountUser accountUser = tokenService.getAccount(token);

        if (batteryNO == null && userMainId == null) {
            userMainId = accountUser.getAccountUserId();
        }

        if (state == null && batteryNO != null && userMainId == null) {
            battery = batteryService.getByNO(batteryNO);
            userMainId = battery.getAccountUserId();
            state = battery.getState();
        }

        List<Battery> batteries = batteryService.getByAccountIdReturn(state, userMainId, accountId);

        return JsonResult.succ(batteries);
    }

    /**
     * 根据区域查看电池状态分组
     */
    @RequestMapping("/stateGroup")
    public JsonResult stateGroup(String token, Integer accountId) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);

        List<BatteryGroupReturn> batteryGroupReturns = batteryService.stateGroup(accountId);

        return JsonResult.succ(batteryGroupReturns);
    }

    /**
     * 根据区域查看人员状态分组
     */
    @RequestMapping("/userIdGroup")
    public JsonResult userIdGroup(String token, Integer accountId) {

        Assert.notNull(accountId, "AccountUser.agentId.notNull");
        AccountUser accountUserToken = tokenService.getAccount(token);

        List<BatteryGroupReturn> batteryGroupReturns = batteryService.userIdGroup(accountId);

        return JsonResult.succ(batteryGroupReturns);
    }

}
